package com.winhxd.b2c.common.oss;

import com.aliyun.oss.OSSClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayInputStream;
import java.io.File;

public class OSSFileUtil {

	private static Logger logger = LoggerFactory.getLogger(OSSFileUtil.class);

	static String endpoint = "oss-cn-beijing.aliyuncs.com";
	static String accessKeyId = "LTAIuMnNZ3CmJI4r";
	static String accessKeySecret = "uKcNvkDax8KrTLrdYCyauIjJ8b1lS7";
	private static String URL_SEPARATOR = "/";
	private static String HOST_SEPARATOR = ".";
	private static String HTTPS = "https://";
	private static String CDN_URL = "https://cdnhxd-outlet.winhxd.com";

	/**
	 *
	 * @param bucketName
	 * @param fileName 包含（path+filename）
	 * @param content
	 *
	 * @desc 目录是以"/" 划分文件目录的
	 */
	public static void uploadFile2OSS(String bucketName, String fileName, byte[] content) {
		try {
			// 创建OSSClient实例。
			OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
			// 上传Byte数组。
			ossClient.putObject(bucketName, fileName, new ByteArrayInputStream(content));
			// 关闭OSSClient。
			ossClient.shutdown();
		} catch (Exception e) {
			logger.error("文件上传失败：" + bucketName + ";FileName : " + fileName, e);
			throw new OSSFileException(OSSFileExceptionCodes.ERROR_CODE_10001, "文件上传失败：" + bucketName + ";FileName : " + fileName);
		}
	}

	/**
	 *
	 * @param bucketName
	 * @param fileName 包含（path+filename）
	 * @param file
	 *  @desc 目录是以"/" 划分文件目录的
	 */
	public static void uploadFile2OSS(String bucketName, String fileName, String file) {
		try {
			// 创建OSSClient实例。
			OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
			// 上传Byte数组。
			ossClient.putObject(bucketName, fileName, new File(file));
			// 关闭OSSClient。
			ossClient.shutdown();
		} catch (Exception e) {
			logger.error("文件上传失败：" + bucketName + ";FileName : " + fileName, e);
			throw new OSSFileException(OSSFileExceptionCodes.ERROR_CODE_10001, "文件上传失败：" + bucketName + ";FileName : " + fileName);
		}
	}

	public static String getFileUrl(String bucketName, String fileName) {
		String path = CDN_URL + URL_SEPARATOR + fileName;
		return path;
	}
}
